//
//  UserDefaults.m
//  OCBase
//
//  Created by 侯伟 on 2019/3/1.
//  Copyright © 2019 侯伟. All rights reserved.
//

#import "UserDefaults.h"


@interface UserDefaults ()

@property(nonatomic,strong)NSUserDefaults *userDefaults;

@end


@implementation UserDefaults


/**
 保存数据
 
 @param object 待保存的数据
 @param key 待保存的键值
 */
+ (void)setData:(id)object forKey:(NSString *)key
{
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:UserDefaultSuiteName];
    
    [userDefaults setValue:object forKey:key];
    [userDefaults synchronize];
}

/**
 获取对应键值的数据
 
 @param key 待取数据的键值
 */
+ (id)getDataForKey:(NSString *)key
{
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:UserDefaultSuiteName];
    
    id object = [userDefaults valueForKey:key];
    
    return object;
}


- (instancetype)init{
    
    if(self = [super init]){
        _userDefaults = [NSUserDefaults standardUserDefaults];
    }
    return self;
}

- (instancetype)initWithName:(NSString*)name{
    if(self = [super init]){
        _userDefaults = [[NSUserDefaults alloc] initWithSuiteName:name];
    }
    return self;
}

/**
 保存数据
 
 @param object 待保存的数据
 @param key 待保存的键值
 */
- (void)setObject:(id)object forKey:(NSString *)key
{
    if(!object){
        [self removeObjectForKey:key];
        return;
    }
    [self.userDefaults setObject:object forKey:key];
    [self commit];
}

/**
 获取对应键值的数据
 
 @param key 待取数据的键值
 */
- (id)objectForKey:(NSString *)key
{
    return [self.userDefaults objectForKey:key];
}

- (NSInteger)integerForKey:(NSString*)key{
    return [self.userDefaults integerForKey:key];
}

- (float)floatForKey:(NSString*)key{
    return [self.userDefaults floatForKey:key];
}

- (double)doubleForKey:(NSString*)key{
    return [self.userDefaults doubleForKey:key];
}

- (NSString*)stringForKey:(NSString*)key{
    return [self.userDefaults stringForKey:key];
}

- (BOOL)boolForKey:(NSString*)key{
    return [self.userDefaults boolForKey:key];
}

- (NSString*)stringForKey:(NSString*)key defaultValue:(NSString*)value{
    NSString* obj = [self.userDefaults stringForKey:key];
    if(obj){
        return obj;
    }else{
        return value;
    }
}

- (NSArray*)arrayForKey:(NSString*)key{
    return  [self.userDefaults arrayForKey:key];
}

- (NSDictionary*)dictionaryForKey:(NSString*)key{
    return [self.userDefaults dictionaryForKey:key];
}

- (NSData*)dataForKey:(NSString*)key{
    return [self.userDefaults dataForKey:key];
}

- (void)removeObjectForKey:(NSString*)key{
    [self.userDefaults removeObjectForKey:key];
    [self commit];
}

- (void)commit{
    [self.userDefaults synchronize];
}
@end
